package hust.ioic.oa.utils;

import hust.ioic.oa.qilin.utils.ConfigFileReader;

import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;



public class FTPUtils {
	/**
	 * 上传文件
	 * @param:@param fileName
	 * @param:@param fileSuffix
	 * @param:@param in
	 * @param:@return
	 * @return: MsgInfo
	 * @author: youpeng
	 * @date:Dec 15, 2015 5:42:40 PM
	 */
	public MsgInfo ftpUploadFile(String fileName, InputStream in) {
		MsgInfo msgInfo = new MsgInfo();
		FTPClient ftp = new FTPClient();
        String resource = "path.properties";
        String ftpUrl = "";
        String port = "";
        String name = "";
        String password = "";
        String savepath = "";
		Properties props = null;
		try {
			props = new Properties();
			InputStream inStream = ConfigFileReader.class.getClassLoader().getResourceAsStream(resource);
			props.load(inStream);
			ftpUrl = props.getProperty("ftpurl");
			port =  props.getProperty("port");
			name = props.getProperty("name");
			password = props.getProperty("password");
			savepath = props.getProperty("savepath");
		} catch (Exception ex) {
			ex.printStackTrace();
			msgInfo.reset(1, "服务器异常");
			return msgInfo;
		}
		
		try {
			// 连接FTP服务器
			ftp.connect(ftpUrl, new Long(port).intValue());

			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(name, password);

			if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
				ftp.disconnect();
				msgInfo.reset(1, "连接FTP服务器失败");
				return msgInfo;
			}
			// 切换工作目录
			if (!ftp.changeWorkingDirectory(savepath)) {
				msgInfo.reset(1, "上传失败");
				return msgInfo;
			}
			
			ftp.setBufferSize(1024); 
			ftp.setControlEncoding("UTF-8" );
			
			// 设置文件类型
			if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) {
				msgInfo.reset(1, "上传失败");
				return msgInfo;
			}
			// FTP协议里面，规定文件名编码为iso-8859-1，所以目录名或文件名需要转码。
			fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");
			// 上传文件
			if(!ftp.storeFile(fileName, in)){
				msgInfo.reset(1, "上传失败");
				return msgInfo;
			}
			
			ftp.logout();
		} catch (Exception e) {
			msgInfo.reset(1, "上传失败");
			return msgInfo;
		}

		return msgInfo;
	}
}
